package com.leff.pvz.scene;

import org.anddev.andengine.entity.Entity;
import org.anddev.andengine.entity.IEntity;
import org.anddev.andengine.util.SmartList;

/**
 * Hack to avoid duplicate parent crashes from AndEngine
 */
public class ShareLayer extends Entity {

	private static final int CHILDREN_CAPACITY_DEFAULT = 4;
	
	@Override
	public void attachChild(IEntity pEntity) throws IllegalStateException {
//		if(pEntity.hasParent()) {
//			throw new IllegalStateException("pEntity already has a parent!");
//		}
		if(this.mChildren == null) {
			this.mChildren = new SmartList<IEntity>(CHILDREN_CAPACITY_DEFAULT);
		}
		this.mChildren.add(pEntity);
		pEntity.setParent(this);
		pEntity.onAttached();
	}

	@Override
	public boolean attachChild(IEntity pEntity, int pIndex) throws IllegalStateException {
//		if(pEntity.hasParent()) {
//			throw new IllegalStateException("pEntity already has a parent!");
//		}
		if (this.mChildren == null) {
			this.mChildren = new SmartList<IEntity>(CHILDREN_CAPACITY_DEFAULT);
		}
		try {
			this.mChildren.add(pIndex, pEntity);
			pEntity.setParent(this);
			pEntity.onAttached();
			return true;
		} catch (final IndexOutOfBoundsException e) {
			return false;
		}
	}
}
